Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

题目大意:使用非递归方式完成二叉树的中序遍历

题目难度:Medium

import java.util.*;
/**
 * Created by gzdaijie on 16/6/5
 * 递归方式
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        midTraversal(root, result);
        return result;
    }

    private void midTraversal(TreeNode root, List<Integer> result) {
        if (root == null) return;
        midTraversal(root.left, result);
        result.add(root.val);
        midTraversal(root.right, result);
    }
}
import java.util.*;
/**
 * Created by gzdaijie on 16/6/5
 * 非递归方式,一旦左节点不为空,将左节点全部入栈
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        midTraversal(root, result);
        return result;
    }

    private void midTraversal(TreeNode root, List<Integer> result) {
        Stack<TreeNode> stack = new Stack<>();
        while (true) {
            while (root != null) {
                stack.add(root);
                root = root.left;
            }
            if (stack.isEmpty()) break;
            TreeNode p = stack.pop();
            result.add(p.val);
            root = p.right;
        }
    }
}
gzdaijie            updated 2016-06-05 17:30:55

results matching ""

    No results matching ""